package br.ufmg.vod.wbr.graphs;

import java.io.IOException;
import java.util.Arrays;

import br.ufmg.vod.wbr.api.Graph;

public class FastGraph implements Graph {
	
	private int[][] neighbours;
	private int undirectedEdgesCount;
	
	public FastGraph(int[][] neighbours) throws IOException{
		this.neighbours = neighbours;
		
		this.undirectedEdgesCount = 0;
		for (int u = 0; u < neighbours.length; u++) {
			Arrays.sort(neighbours[u]);
			int[] oldArray = neighbours[u];
			for (int i = 0; i < oldArray.length; i++) {
				if( oldArray[i] >= neighbours.length){
					int[] newArray = new int[i];
					System.arraycopy(oldArray, 0, newArray, 0, i);
					neighbours[u] = newArray;
					break;
				}
			}
			this.undirectedEdgesCount += neighbours[u].length;
		}
	}


	@Override
	public boolean containsEdge(int vertex1, int vertex2) {
		return Arrays.binarySearch( this.neighbours[vertex1], vertex2) != -1;
	}

	@Override
	public boolean containsVertex(int vertex) {
		return vertex >= 0 && vertex < this.neighbours.length;
	}

	@Override
	public int[][] getAllEdges() {
		return this.neighbours;
	}

	@Override
	public int getDegree(int vertex) {
		return this.neighbours[vertex].length;
	}

	@Override
	public int[] getEdges(int vertex) {
		return this.neighbours[vertex];
	}

	@Override
	public int getNumEdges() {
		return this.undirectedEdgesCount;
	}

	@Override
	public int getNumVertex() {
		return this.neighbours.length;
	}


}